<template>
  <div class="booking-form">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑预约' : '新建预约' }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        style="max-width: 600px;"
      >
        <el-form-item label="会议室" prop="roomId">
          <el-select
            v-model="form.roomId"
            placeholder="请选择会议室"
            style="width: 100%"
            @change="handleRoomChange"
          >
            <el-option
              v-for="room in availableRooms"
              :key="room.id"
              :label="`${room.name} (${room.location})`"
              :value="room.id"
            >
              <div class="room-option">
                <div>{{ room.name }}</div>
                <div class="room-info">
                  <span>{{ room.location }}</span>
                  <span>容纳{{ room.capacity }}人</span>
                  <el-tag size="small" :type="getStatusType(room.status)">
                    {{ getStatusText(room.status) }}
                  </el-tag>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="预约日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
            style="width: 100%"
            @change="handleDateChange"
          />
        </el-form-item>

        <el-form-item label="时间段" prop="timeRange">
          <el-time-picker
            v-model="form.startTime"
            placeholder="开始时间"
            format="HH:mm"
            value-format="HH:mm"
            :disabled-hours="disabledHours"
            style="width: 45%; margin-right: 10px;"
          />
          <span style="margin: 0 10px;">至</span>
          <el-time-picker
            v-model="form.endTime"
            placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            :disabled-hours="disabledHours"
            style="width: 45%;"
          />
        </el-form-item>

        <el-form-item label="用途" prop="purpose">
          <el-input
            v-model="form.purpose"
            placeholder="请输入会议用途"
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="参会人数" prop="attendees">
          <el-input-number
            v-model="form.attendees"
            :min="1"
            :max="selectedRoom ? selectedRoom.capacity : 100"
            placeholder="请输入参会人数"
            style="width: 100%"
          />
          <div class="form-tip" v-if="selectedRoom">
            该会议室最多可容纳 {{ selectedRoom.capacity }} 人
          </div>
        </el-form-item>

        <el-form-item label="联系人" prop="contact">
          <el-input
            v-model="form.contact"
            placeholder="请输入联系人姓名"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入联系电话"
          />
        </el-form-item>

        <el-form-item label="设备需求">
          <el-checkbox-group v-model="form.equipment">
            <el-checkbox label="投影仪" />
            <el-checkbox label="白板" />
            <el-checkbox label="音响" />
            <el-checkbox label="视频会议" />
            <el-checkbox label="空调" />
            <el-checkbox label="WiFi" />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            placeholder="请输入备注信息"
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交预约</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 会议室可用性提示 -->
    <el-card v-if="selectedRoom" style="margin-top: 20px;">
      <template #header>
        <span>会议室可用性</span>
      </template>
      <div class="availability-info">
        <div class="room-detail">
          <h4>{{ selectedRoom.name }}</h4>
          <p>位置：{{ selectedRoom.location }}</p>
          <p>容量：{{ selectedRoom.capacity }}人</p>
          <p>设备：{{ selectedRoom.equipment.join('、') }}</p>
        </div>
        <div class="time-slots" v-if="form.date">
          <h4>当日预约情况</h4>
          <div class="time-grid">
            <div
              v-for="slot in timeSlots"
              :key="slot.time"
              :class="['time-slot', { 'booked': slot.booked }]"
            >
              <span class="time">{{ slot.time }}</span>
              <span class="status">{{ slot.booked ? '已预约' : '可用' }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

// 会议室数据
const availableRooms = ref([
  {
    id: 1,
    name: '会议室A',
    location: '1楼101',
    capacity: 10,
    equipment: ['投影仪', '白板', '音响'],
    status: 'available'
  },
  {
    id: 2,
    name: '会议室B',
    location: '2楼201',
    capacity: 20,
    equipment: ['投影仪', '白板', '音响', '视频会议'],
    status: 'available'
  },
  {
    id: 3,
    name: '会议室C',
    location: '3楼301',
    capacity: 5,
    equipment: ['白板', 'WiFi'],
    status: 'maintenance'
  }
])

// 表单数据
const form = reactive({
  roomId: '',
  date: '',
  startTime: '',
  endTime: '',
  purpose: '',
  attendees: 1,
  contact: '',
  phone: '',
  equipment: [],
  remark: ''
})

// 表单验证规则
const rules = {
  roomId: [
    { required: true, message: '请选择会议室', trigger: 'change' }
  ],
  date: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  purpose: [
    { required: true, message: '请输入会议用途', trigger: 'blur' }
  ],
  attendees: [
    { required: true, message: '请输入参会人数', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const formRef = ref()
const isEdit = ref(false)

// 选中的会议室
const selectedRoom = computed(() => {
  return availableRooms.value.find(room => room.id === form.roomId)
})

// 时间段数据
const timeSlots = ref([
  { time: '09:00-10:00', booked: false },
  { time: '10:00-11:00', booked: true },
  { time: '11:00-12:00', booked: false },
  { time: '12:00-13:00', booked: false },
  { time: '13:00-14:00', booked: false },
  { time: '14:00-15:00', booked: true },
  { time: '15:00-16:00', booked: false },
  { time: '16:00-17:00', booked: false },
  { time: '17:00-18:00', booked: false }
])

// 获取状态类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    available: 'success',
    maintenance: 'warning',
    disabled: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    available: '可用',
    maintenance: '维护中',
    disabled: '已停用'
  }
  return texts[status] || '未知'
}

// 禁用日期（只能选择今天及以后的日期）
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 禁用小时（工作时间 9:00-18:00）
const disabledHours = () => {
  const hours = []
  for (let i = 0; i < 24; i++) {
    if (i < 9 || i >= 18) {
      hours.push(i)
    }
  }
  return hours
}

// 会议室选择变化
const handleRoomChange = () => {
  // 重置参会人数
  if (selectedRoom.value) {
    form.attendees = Math.min(form.attendees, selectedRoom.value.capacity)
  }
}

// 日期变化
const handleDateChange = () => {
  // 这里可以根据选择的日期和会议室获取实际的预约情况
  console.log('日期变化:', form.date)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 验证时间
    if (form.startTime >= form.endTime) {
      ElMessage.error('结束时间必须晚于开始时间')
      return
    }

    // 验证参会人数
    if (selectedRoom.value && form.attendees > selectedRoom.value.capacity) {
      ElMessage.error(`参会人数不能超过会议室容量(${selectedRoom.value.capacity}人)`)
      return
    }

    // 模拟提交
    const bookingData = {
      ...form,
      roomName: selectedRoom.value?.name,
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      status: 'pending'
    }

    console.log('预约数据:', bookingData)
    ElMessage.success('预约提交成功，请等待管理员确认')

    // 重置表单
    formRef.value.resetFields()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

onMounted(() => {
  // 设置默认日期为今天
  form.date = dayjs().format('YYYY-MM-DD')
})
</script>

<style scoped lang="scss">
.booking-form {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.room-option {
  .room-info {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;

    span {
      margin-right: 10px;
    }
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.availability-info {
  .room-detail {
    margin-bottom: 20px;

    h4 {
      margin: 0 0 10px 0;
      color: #303133;
    }

    p {
      margin: 5px 0;
      color: #606266;
    }
  }

  .time-slots {
    h4 {
      margin: 0 0 15px 0;
      color: #303133;
    }

    .time-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
      gap: 10px;

      .time-slot {
        padding: 8px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        text-align: center;

        &.booked {
          background-color: #f5f7fa;
          border-color: #e4e7ed;

          .status {
            color: #f56c6c;
          }
        }

        .time {
          display: block;
          font-size: 12px;
          color: #606266;
        }

        .status {
          display: block;
          font-size: 12px;
          color: #67c23a;
          margin-top: 4px;
        }
      }
    }
  }
}
</style>